import type { MockMethod } from 'vite-plugin-mock'
import Mock from 'mockjs'
import type { User, UserQuery, CreateUser, UpdateUser, ResetPassword } from '../../src/types/api/system/user'
import type { API } from '../../src/types/api/response'

const Random = Mock.Random

// ------------ 常量定义 ------------
// 定义部门信息
interface Department {
  id: string;
  name: string;
  children?: Department[];
}

const departments: Department[] = [
  { id: '1', name: '技术部', children: [
    { id: '1-1', name: '研发中心', children: [
      { id: '1-1-1', name: '前端组' },
      { id: '1-1-2', name: '后端组' },
      { id: '1-1-3', name: '测试组' },
      { id: '1-1-4', name: 'DevOps组' }
    ]},
    { id: '1-2', name: '产品中心', children: [
      { id: '1-2-1', name: '产品设计组' },
      { id: '1-2-2', name: 'UI设计组' }
    ]}
  ]},
  { id: '2', name: '销售部', children: [
    { id: '2-1', name: '国内销售组' },
    { id: '2-2', name: '海外销售组' }
  ]},
  { id: '3', name: '市场部', children: [
    { id: '3-1', name: '市场策划组' },
    { id: '3-2', name: '市场推广组' },
    { id: '3-3', name: '公关媒体组' }
  ]},
  { id: '4', name: '人事行政部', children: [
    { id: '4-1', name: '人力资源组' },
    { id: '4-2', name: '行政管理组' },
    { id: '4-3', name: '培训发展组' }
  ]},
  { id: '5', name: '财务部', children: [
    { id: '5-1', name: '会计核算组' },
    { id: '5-2', name: '财务管理组' }
  ]},
  { id: '6', name: '客户服务部', children: [
    { id: '6-1', name: '客户支持组' },
    { id: '6-2', name: '售后服务组' }
  ]}
]

// 定义角色信息
const roles = [
  { id: 'admin', roleName: '系统管理员', description: '拥有系统所有权限' },
  { id: 'hr', roleName: '人力资源管理员', description: '管理用户、部门、薪资等' },
  { id: 'dev', roleName: '开发人员', description: '产品开发及测试权限' },
  { id: 'pm', roleName: '产品经理', description: '产品管理及规划权限' },
  { id: 'sale', roleName: '销售人员', description: '客户管理及销售数据权限' },
  { id: 'marketing', roleName: '市场专员', description: '市场活动及数据分析权限' },
  { id: 'finance', roleName: '财务人员', description: '财务数据及报表权限' },
  { id: 'cs', roleName: '客服专员', description: '客户服务及工单处理权限' },
  { id: 'user', roleName: '普通用户', description: '基础功能使用权限' },
  { id: 'guest', roleName: '访客', description: '只读权限' }
]

// 名字前缀，用于生成更真实的用户名
const namePrefix = ['zhang', 'wang', 'li', 'zhao', 'chen', 'yang', 'wu', 'liu', 'huang', 'zhou', 
                    'xu', 'sun', 'ma', 'zhu', 'hu', 'guo', 'lin', 'luo', 'cheng', 'he', 
                    'gao', 'peng', 'liang', 'xie', 'cao', 'wei']

// 手机号前缀
const phonePrefixes = ['138', '139', '137', '136', '135', '134', '159', '158', '157', '150', 
                       '151', '152', '188', '187', '182', '183', '184', '178', '170', '176']

// 常用邮箱域名
const emailDomains = ['gmail.com', 'qq.com', '163.com', '126.com', 'outlook.com', 'hotmail.com', 
                     'yahoo.com', 'foxmail.com', 'sina.com', 'sohu.com', 'aliyun.com', 'yeah.net',
                     'company.com', 'example.org', 'example.net']

// ------------ 工具函数 ------------
/**
 * 从部门树中随机选择一个部门
 */
const getRandomDepartment = () => {
  // 随机选择一个顶级部门
  const topDept = Random.pick(departments)
  
  // 如果有子部门，随机决定是使用顶级部门还是子部门
  if (topDept.children && Random.boolean()) {
    const childDept = Random.pick(topDept.children)
    
    // 如果子部门还有子部门，随机决定是否继续下探
    if (childDept.children && Random.boolean()) {
      const grandChildDept = Random.pick(childDept.children)
      return { id: grandChildDept.id, name: grandChildDept.name }
    }
    
    return { id: childDept.id, name: childDept.name }
  }
  
  return { id: topDept.id, name: topDept.name }
}

/**
 * 随机生成1-3个角色
 */
const getRandomRoles = () => {
  // 随机决定用户拥有的角色数量（1-3个）
  const roleCount = Random.integer(1, 3)
  
  // 复制角色数组以避免修改原数组
  const availableRoles = [...roles]
  const userRoles = []
  
  // 随机选择指定数量的角色
  for (let i = 0; i < roleCount && availableRoles.length > 0; i++) {
    // 随机选择一个角色索引
    const randomIndex = Random.integer(0, availableRoles.length - 1)
    // 取出该角色
    const role = availableRoles.splice(randomIndex, 1)[0]
    userRoles.push({ id: role.id, roleName: role.roleName })
  }
  
  return userRoles
}

/**
 * 生成真实风格的用户名
 */
const generateUsername = (index: number) => {
  // 一定概率使用名字拼音+数字的格式
  if (Random.boolean()) {
    const prefix = Random.pick(namePrefix)
    // 随机生成1-3位数字后缀
    const suffix = Random.string('number', 1, 3)
    return `${prefix}${suffix}`
  }
  
  // 一定概率使用职位缩写+数字的格式
  if (Random.boolean()) {
    const prefix = Random.pick(['dev', 'pm', 'hr', 'admin', 'ops', 'test', 'ui', 'ux', 'sale', 'fin', 'mkt'])
    const suffix = Random.string('number', 2, 4)
    return `${prefix}${suffix}`
  }
  
  // 默认格式：user+序号
  return `user${index + 1}`
}

/**
 * 生成真实风格的邮箱
 */
const generateEmail = (username: string) => {
  const domain = Random.pick(emailDomains)
  
  // 有一定概率邮箱前缀与用户名一致
  if (Math.random() < 0.7) {
    return `${username}@${domain}`
  }
  
  // 其他情况生成随机邮箱
  return Random.email(domain)
}

/**
 * 生成真实风格的手机号码
 */
const generatePhone = () => {
  const prefix = Random.pick(phonePrefixes)
  const suffix = Random.string('number', 8)
  return `${prefix}${suffix}`
}

/**
 * 生成模拟用户数据
 */
const generateMockUsers = (count: number = 130): User[] => {
  return Array.from({ length: count }, (_, index) => {
    // 生成用户名
    const username = generateUsername(index)
    
    // 生成姓名
    const nickname = Random.cname()
    
    // 生成邮箱和手机号
    const email = generateEmail(username)
    const phone = generatePhone()
    
    // 随机获取部门和角色
    const dept = getRandomDepartment()
    const roles = getRandomRoles()
    
    // 生成注册时间（1年内的随机时间）
    const now = new Date()
    const oneYearAgo = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate())
    const createTime = Random.datetime('yyyy-MM-dd HH:mm:ss')
    
    // 大部分用户是启用状态
    const status = Math.random() < 0.9 ? 1 : 0
    
    return {
      id: Random.guid(),
      username,
      nickname,
      email,
      phone,
      status,
      dept,
      roles,
      createTime,
      statusLoading: false
    }
  })
}

// ------------ 模拟数据 ------------
// 生成用户数据，并确保至少有一个系统管理员
const users: User[] = generateMockUsers()

// 确保第一个用户是超级管理员
users[0] = {
  id: '1',
  username: 'admin',
  nickname: '系统管理员',
  email: 'admin@example.com',
  phone: '13800000000',
  status: 1,
  dept: { id: '1', name: '技术部' },
  roles: [{ id: 'admin', roleName: '系统管理员' }],
  createTime: '2022-01-01 00:00:00',
  statusLoading: false
}

// ------------ API 实现 ------------
/**
 * 获取用户列表
 */
const getUserListApi: MockMethod = {
  url: '/api/system/user/list',
  method: 'get',
  response: ({ query }: { query: UserQuery }): API.Response<{ list: User[]; total: number }> => {
    const { keyword, page = 1, pageSize = 10, deptId, status } = query

    // 确保 page 和 pageSize 是数字类型
    const pageNum = Number(page)
    const pageSizeNum = Number(pageSize)

    let filteredUsers = [...users]

    // 关键字搜索
    if (keyword) {
      filteredUsers = filteredUsers.filter(user => 
        user.username.includes(keyword) || 
        (user.nickname && user.nickname.includes(keyword)) || 
        (user.email && user.email.includes(keyword)) ||
        (user.phone && user.phone.includes(keyword))
      )
    }

    // 部门筛选
    if (deptId) {
      filteredUsers = filteredUsers.filter(user => user.dept.id === deptId)
    }

    // 状态筛选
    if (status !== undefined) {
      filteredUsers = filteredUsers.filter(user => user.status === status)
    }

    // 分页
    const startIndex = (pageNum - 1) * pageSizeNum
    const endIndex = startIndex + pageSizeNum
    console.log('startIndex', startIndex)
    console.log('endIndex', endIndex)
    console.log('pageSize type:', typeof pageSizeNum, 'value:', pageSizeNum)
    const pagedUsers = filteredUsers.slice(startIndex, endIndex)

    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        list: pagedUsers,
        total: filteredUsers.length
      }
    }
  }
}

/**
 * 获取用户详情
 */
const getUserDetailApi: MockMethod = {
  url: '/api/system/user/:id',
  method: 'get',
  response: ({ query }: { query: { id: string } }): API.Response<User | null> => {
    const { id } = query
    const user = users.find(u => u.id === id)
    
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: user || null
    }
  }
}

/**
 * 创建用户
 */
const createUserApi: MockMethod = {
  url: '/api/system/user',
  method: 'post',
  response: ({ body }: { body: CreateUser }): API.Response<User | null> => {
    // 获取随机部门和角色信息
    const findDepartment = (deptId: string): Department | undefined => {
      // 平铺所有部门，包括子部门
      const allDepartments: Department[] = [
        ...departments,
        ...departments.flatMap(d => d.children || []),
        ...departments.flatMap(d => (d.children || []).flatMap(c => c.children || []))
      ];
      return allDepartments.find(d => d.id === deptId);
    };
    
    const deptInfo = findDepartment(body.deptId) || { id: body.deptId, name: '未知部门' };
    
    const roleInfos = body.roleIds?.map(roleId => {
      const role = roles.find(r => r.id === roleId);
      return { id: roleId, roleName: role?.roleName || '未知角色' };
    }) || [];

    const newUser: User = {
      id: Random.guid(),
      username: body.username,
      nickname: body.nickname,
      email: body.email,
      phone: body.phone,
      status: body.status || 1,
      dept: {
        id: body.deptId,
        name: deptInfo.name
      },
      roles: roleInfos,
      createTime: new Date().toISOString(),
      statusLoading: false
    }
    
    users.unshift(newUser)
    
    return {
      code: 200,
      success: true,
      message: '创建成功',
      data: newUser
    }
  }
}

/**
 * 更新用户
 */
const updateUserApi: MockMethod = {
  url: '/api/system/user/:id',
  method: 'put',
  response: ({ body, query }: { body: UpdateUser, query: { id: string } }): API.Response<null> => {
    const index = users.findIndex(u => u.id === query.id)
    if (index > -1) {
      const user = users[index]
      
      // 获取部门信息
      let deptInfo = { name: user.dept.name };
      if (body.deptId) {
        // 平铺所有部门，包括子部门
        const allDepartments: Department[] = [
          ...departments,
          ...departments.flatMap(d => d.children || []),
          ...departments.flatMap(d => (d.children || []).flatMap(c => c.children || []))
        ];
        const dept = allDepartments.find(d => d.id === body.deptId);
        deptInfo = dept || { id: body.deptId, name: '未知部门' };
      }
      
      // 获取角色信息
      const roleInfos = body.roleIds?.map(roleId => {
        const role = roles.find(r => r.id === roleId);
        return { id: roleId, roleName: role?.roleName || '未知角色' };
      });
      
      users[index] = {
        ...user,
        ...(body.nickname && { nickname: body.nickname }),
        ...(body.email && { email: body.email }),
        ...(body.phone && { phone: body.phone }),
        ...(body.status !== undefined && { status: body.status }),
        ...(body.deptId && {
          dept: {
            id: body.deptId,
            name: deptInfo.name
          }
        }),
        ...(roleInfos && { roles: roleInfos })
      }
    }
    
    return {
      code: 200,
      success: true,
      message: '更新成功',
      data: null
    }
  }
}

/**
 * 删除用户
 */
const deleteUserApi: MockMethod = {
  url: '/api/system/user',
  method: 'delete',
  response: ({ body }: { body: { ids: string[] } }): API.Response<null> => {
    const { ids } = body
    ids.forEach(id => {
      const index = users.findIndex(u => u.id === id)
      if (index > -1) {
        users.splice(index, 1)
      }
    })
    
    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }
}

/**
 * 修改用户状态
 */
const changeUserStatusApi: MockMethod = {
  url: '/api/system/user/:id/status',
  method: 'put',
  response: ({ body, query }: { body: { status: 0 | 1 }, query: { id: string } }): API.Response<null> => {
    const user = users.find(u => u.id === query.id)
    if (user) {
      user.status = body.status
    }
    
    return {
      code: 200,
      success: true,
      message: '状态修改成功',
      data: null
    }
  }
}

/**
 * 重置密码
 */
const resetPasswordApi: MockMethod = {
  url: '/api/system/user/:id/password',
  method: 'put',
  response: ({ body }: { body: ResetPassword }): API.Response<null> => {
    return {
      code: 200,
      success: true,
      message: '密码重置成功',
      data: null
    }
  }
}

/**
 * 分配角色
 */
const assignRolesApi: MockMethod = {
  url: '/api/system/user/:id/roles',
  method: 'put',
  response: ({ body, query }: { body: { roleIds: string[] }, query: { id: string } }): API.Response<null> => {
    const user = users.find(u => u.id === query.id)
    if (user) {
      // 获取角色信息
      const roleInfos = body.roleIds.map(roleId => {
        const role = roles.find(r => r.id === roleId);
        return { id: roleId, roleName: role?.roleName || '未知角色' };
      });
      
      user.roles = roleInfos
    }
    
    return {
      code: 200,
      success: true,
      message: '角色分配成功',
      data: null
    }
  }
}

// ------------ 导出 ------------
export default [
  getUserListApi,
  getUserDetailApi,
  createUserApi,
  updateUserApi,
  deleteUserApi,
  changeUserStatusApi,
  resetPasswordApi,
  assignRolesApi
] as MockMethod[] 